const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            tableData: [{
                COLUMN_NAME: 'A1',
                COLUMN_COMMENT: '',
                LABEL_TYPE: 'input',
                REQUIRED: '0',
                DATA: [{
                    label: ''
                }],
            }],
            dataForm:{
                Questionnaire_Notes:'',
                Row_Status:'2'
            },
            label: [{
                label: '文本框',
                value: 'input'
            }, {
                label: '文本域',
                value: 'textarea'
            }, {
                label: '选择器',
                value: 'select',
            }, {
                label: '单选框',
                value: 'radio',
            }, {
                label: '多选框',
                value: 'checkbox',
            }],
            city: []
        };
    },
    mounted() {
        this.getCategory();
    },
    methods: {
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/clientOperation/getDistrictTree`,
                type: "GET",
                data: {
                    DistrictCode: "232723"
                },
                success: (data) => {
                    this.city = data[0].children;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        handleData(item) {
            item.DATA.push({
                label: ''
            })
        },
        RemoveData(item, index) {
            item.DATA = item.DATA.filter((i, id) => id != index);
        },
        handleColumnAdd() {
            this.tableData.push({
                COLUMN_NAME: 'A' + (this.tableData.length + 1),
                LABEL_TYPE: 'input',
                COLUMN_COMMENT: '',
                REQUIRED: '0',
                DATA: [{
                    label: ''
                }],
            })
        },
        handleColumnRemove() {
            if (this.tableData.length > 1) {
                this.tableData.pop();
            } else {
                this.$message({
                    message: '不能再删除了',
                    type: 'warning'
                });
            }
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数

                if (action == 'Add') {
                    let TABLE_NAME = 'questionnaire_form' + (+new Date());
                    this.dataForm.From_JSON = JSON.stringify(this.tableData);
                    this.dataForm.Table_Name = TABLE_NAME;
                    let lJSONObject_DataSet = {
                        Add: {
                            document_rule: [{//主键自动递增规则
                                Document_Name: TABLE_NAME,
                                Document_Head: 'QF',
                                Document_SerialNumber: '0',
                                Document_Length: '15'
                            }],
                            questionnaire: [this.dataForm]
                        },
                    }
                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '0',
                        Operation_Path: this.relativePath,
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]
                    submitSave(lJSONObject_DataSet, (res) => {
                        if (res.Status == 'success') {
                            $.ajax({
                                headers: requestHeaders(),
                                url: `${mh}/generalBusiness/generalDataTableOperation`,
                                type: 'POST',
                                data: { Data: this.CREATE_TABLE(TABLE_NAME) },
                                success: (res) => {
                                    if (res.Status == 'success') {
                                        $.ajax({
                                            headers: requestHeaders(),
                                            url: `${mh}/generalBusiness/generalSaveFiles`,
                                            type: 'POST',
                                            data: {
                                                Data: JSON.stringify({
                                                    FileName: TABLE_NAME,
                                                    FileContent: window.btoa(unescape(encodeURIComponent(encodeURIComponent(this.CREATE_PAGE(TABLE_NAME)))))
                                                })
                                            },
                                            success: (res) => {
                                                if (res.Status == 'success') {
                                                    window.location.href = './index.html';
                                                    this.loading = false;
                                                }
                                            },
                                            complete: function (XMLHttpRequest) {
                                                requestPretreatment(XMLHttpRequest);
                                            },
                                            dataType: "json"
                                        })
                                    }
                                },
                                complete: (XMLHttpRequest) => {
                                    requestPretreatment(XMLHttpRequest);
                                },
                                dataType: "json"
                            })
                        }
                    });
                }
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
        CREATE_TABLE(TABLE_NAME) {
            let systemList = [
                { COLUMN_NAME: 'Creater_SerialNumber', COLUMN_COMMENT: '创建人' },
                { COLUMN_NAME: 'Create_Datetime', COLUMN_COMMENT: '创建时间' },
                { COLUMN_NAME: 'Row_Status', COLUMN_COMMENT: '行状态' },
                { COLUMN_NAME: 'Operation_ID', COLUMN_COMMENT: '操作人' },
                { COLUMN_NAME: 'Operation_Datetime', COLUMN_COMMENT: '操作时间' }
            ]
            //表名 CREATE TABLE省略
            let SQL = "`" + TABLE_NAME + "` (\r\n" + "`Questionnaire_Form_SerialNumber` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '调查问卷填写流水号',\r\n";
            // SQL = SQL + "`Questionnaire_SerialNumber` " + "varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '调查问卷配置流水号',\r\n";
            //字段
            [...this.tableData, ...systemList].forEach(item => {
                SQL = SQL + "`" + item.COLUMN_NAME + "` " + "varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '" + item.COLUMN_COMMENT + "',\r\n";
            })
            //主键
            SQL = SQL + "PRIMARY KEY (`Questionnaire_Form_SerialNumber`)\r\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='" + this.dataForm.Questionnaire_Name + "';";
            return SQL;
        },
        CREATE_PAGE(TABLE_NAME) {
            return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="../yl/index.css" />
    <link rel="stylesheet" href="../yl/style.css" />
    <link rel="stylesheet" href="../style/free.css" />
    <title>调查问卷</title>
    <style>
        .el-select__wrapper{
            box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
            background-color: var(--el-fill-color-blank) !important;
        }
        .el-form-item__label {
            justify-content: flex-start;
        }
    </style>
</head>
<body>
    <div id="app" v-cloak>
        <el-form :model="form" ref="form" style="width: 100%; height: calc(100vh - 120rem); overflow: auto;">
            <div class="m-2 rounded flex flex-column">
                ${this.tableData.map((obj, index) => `<el-form-item ${obj.REQUIRED == '1' ? `:rules="[{ required: true, message: '请输入${obj.COLUMN_COMMENT}', trigger: '${obj.LABEL_TYPE == 'input' || obj.LABEL_TYPE == 'textarea' ? 'blur' : 'change'}' }]"` : ''} prop="${obj.COLUMN_NAME}" class="m-2 flex flex-column">
                    <template #label>
                        <span class="font flex-shrink">${index + 1}.${obj.COLUMN_COMMENT}:</span>
                    </template>
                    ${obj.LABEL_TYPE == 'input' ? `<el-input v-model="form.${obj.COLUMN_NAME}" placeholder="请输入${obj.COLUMN_COMMENT}"></el-input>`
                    : obj.LABEL_TYPE == 'textarea' ? `<el-input type="textarea" :autosize="{ minRows: 4}" v-model="form.${obj.COLUMN_NAME}" placeholder="请输入${obj.COLUMN_COMMENT}"></el-input>`
                        : obj.LABEL_TYPE == 'select' ? `<el-select v-model="form.${obj.COLUMN_NAME}" placeholder="请选择${obj.COLUMN_COMMENT}">
                        <el-option v-for="(item,index) in [${obj.DATA.map(i => "'" + i.label + "'").join(',')}]" :key="index" :label="item" :value="item"></el-option>
                    </el-select>`
                            : obj.LABEL_TYPE == 'radio' ? `<el-radio-group v-model="form.${obj.COLUMN_NAME}">
                        <el-radio :label="item" v-for="(item,index) in [${obj.DATA.map(i => "'" + i.label + "'").join(',')}]" :key="index"></el-radio>
                    </el-radio-group>`
                                : `<el-checkbox-group v-model="form.${obj.COLUMN_NAME}">
                        <el-checkbox :label="item" v-for="(item,index) in [${obj.DATA.map(i => "'" + i.label + "'").join(',')}]" :key="index"></el-checkbox>
                    </el-checkbox-group>`}
                </el-form-item>`).join('\n')}
            </div>
        </el-form>
        <div class="fixed-bottom flex justify-center w-100 bg-white shadow" style="height: 120rem; ">
            <div @click="handleSubmit" class=" m-2 bg-info rounded-circle w-100 flex justify-center align-center" v-cloak>
                <span class="text-white">提交表单</span>
            </div>
        </div>
    </div>
    <script src="../utils/utils.js"></script>
    <script src="../utils/mixins.js"></script>
    <script src="../config/config.js"></script>
    <script src="../yl/vue.js"></script>
    <script src="../yl/index.js"></script>
    <script src="../yl/zh-cn.mjs"></script>
    <script src="../yl/index.iife.min.js"></script>
    <script src="../yl/jquery.min.js"></script>
    <script src="../utils/jquery.cookie.js"></script>
    <script src="../api/request.js"></script>
    <script src="../utils/jweixin.js"></script>
    <script>
        const App = {
            data() {
                return {
                    form: {
                        ${this.tableData.filter(i => i.LABEL_TYPE == 'checkbox').map(i => i.COLUMN_NAME + ':[],')}
                    },
                }
            },
            beforeCreate() {
                document.title = "${this.dataForm.Questionnaire_Name}";
                function setRem() {
                    const designWidth = 750; // 设计稿宽度（rpx）
                    const maxWidth = 540; // 可选：限制最大宽度（如手机端常见值）
                    const screenWidth = Math.min(window.innerWidth, maxWidth);
                    const scale = screenWidth / designWidth;
                    document.documentElement.style.fontSize = scale + 'px';
                }
                setRem();//1rem = 0.5px 对标小程序在 375px 宽的屏幕上，1rpx = 0.5px（因为 750rpx / 375px = 2）
                window.addEventListener('resize', setRem);
            },
            mounted() {
                let URL = window.location.href;
                this.form.Questionnaire_SerialNumber = getQueryObject(URL,'nodeKey');
            },
            methods: {
                async validateAllForms() {
                    //获取当前页面上所有的Elform
                    let forms = [];
                    for (let key in this.$refs) {
                        const ref = this.$refs[key];
                        if (ref.$options && ref.$options.name == 'ElForm') {
                            forms.push(ref);
                        }
                    }
                    //判断每个Elform的校验是否通过
                    let isfail = false;
                    for (const form of forms) {
                        try {
                            await form.validate();
                        } catch (error) {
                            isfail = true;
                        }
                    }
                    if (isfail) {
                        return false;
                    }
                    return true;
                },
                async handleSubmit() {
                    const allValid = await this.validateAllForms();
                    if (allValid && !this.loading) {
                        this.loading = true;
                        const Points = ${this.dataForm.Points};
                        let form = deepClone(this.form);
                        ${this.tableData.filter(i => i.LABEL_TYPE == 'checkbox').map(i => 'form.' + i.COLUMN_NAME + '= JSON.stringify(form.' + i.COLUMN_NAME + ');\r\n')}
                        $.ajax({
                            headers: requestHeaders(),
                            url: mh + '/population/getPersonalPoint',
                            method: "GET",
                            success: (personal_points_account) => {
                                let lJSONObject_DataSet = new Object();

                                let personal_points_change_log = {
                                    ID_Card_Number: '',
                                    Points_Title: '填写调查问卷获取积分',
                                    Points_Type: '0',
                                    Change_Points: Points,
                                    Notes: '填写调查问卷获取积分',
                                }

                                if (personal_points_account.length == 1) {//有账户
                                    const Total_Points = accAdd(personal_points_account[0].Total_Points, Points);
                                    const Remain_Points = accAdd(personal_points_account[0].Remain_Points, Points);
                                    personal_points_account[0].Total_Points = Total_Points;
                                    personal_points_account[0].Remain_Points = Remain_Points;
                                    lJSONObject_DataSet = {
                                        Add: {
                                            ${TABLE_NAME}: [form],
                                            personal_points_change_log: [{
                                                ...personal_points_change_log,
                                                Remain_Points,
                                            }],
                                        },
                                        Modify: {
                                            personal_points_account,
                                        }
                                    }
                                } else {//无账户
                                    lJSONObject_DataSet = {
                                        Add: {
                                            ${TABLE_NAME}: [form],
                                            personal_points_change_log: [{
                                                ...personal_points_change_log,
                                                Remain_Points: Points
                                            }],
                                            personal_points_account: [{
                                                ID_Card_Number: '',
                                                Points_Type: '0',
                                                Total_Points: Points,
                                                Remain_Points: Points,
                                                Sales_Points: '0'
                                            }]
                                        },
                                    }
                                }
                                this.submitSave(lJSONObject_DataSet, (res) => {
                                    if (res.Status == 'success') {
                                        window.history.back();
                                    }
                                    this.loading = false;
                                })
                            },
                            complete: (XMLHttpRequest) => {
                                if (XMLHttpRequest.status == 302) {
                                    wx.miniProgram.navigateTo({
                                        url: miniProgram,
                                    })
                                }
                            },
                            dataType: "json"
                        })
                    }
                },
                submitSave(Data, response) {
                    const websocket = new WebSocketClient();
                    websocket.init({
                        url: ws + '/generalSave/' + getCookie('token'),
                        onopen: () => {
                            let lJSONObject_DataSet = {
                                Data, AccessToken: getCookie('token'),
                                replaceParameter: "ID_Card_Number",
                            }
                            websocket.send(JSON.stringify(lJSONObject_DataSet));
                        },
                        onmessage: (data) => {
                            try {
                                const res = JSON.parse(data);
                                websocket.close();
                                if (res.REDIRECT && res.REDIRECT == 'REDIRECT') {//重定向
                                    wx.miniProgram.navigateTo({
                                        url: '',
                                    })
                                } else {
                                    response ? response(res) : null;
                                }
                            } catch (error) { }
                        },
                    })
                }
            },
        };
            
        const { createApp } = Vue;
        const app = createApp(App);
        //这种方式是引入全部图标，无需单个引入
        for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
            app.component(key, component);
        }
        const ElMessage = ElementPlus.ElMessage;
        app.use(ElementPlus, { locale: zhCn });
        app.mount("#app");
    </script>
</body>
</html>`
        }
    }
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-text-editor', ylTextEditor);
app.component('yl-cascader', ylCascader);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
